﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;
using System.Text.RegularExpressions;
using System.Globalization;
using System.IO;
using System.Collections;

namespace OnlineZeitenTool
{
    public partial class FrmOnlineZeitenTool : Form
    {
        private int TEIL_DER_STUNDE = 30;
        private String VersionsNummer = " Version: 1.04";
        private static String fileName = Environment.CurrentDirectory + "\\Zeiten.xml";
        Pabo.Calendar.DateItem[] datesForPlayer = null;
       
        public FrmOnlineZeitenTool()
        {
            InitializeComponent();
            this.Text += VersionsNummer;
            ToolStripControlHost dtTScomponent = new ToolStripControlHost(dTStartSuche);
            toolStrip1.Items.Add(dtTScomponent); 

        }

        private void AddToXml(Dictionary<string, List<DateTime>> dic)
        {
            try
            {
                XElement root = XElement.Load(fileName);
                //MessageBox.Show("gefundene Spieler: in Datei: " + fileName + " " + root.Elements("Spieler").Count());
                
               toolStripProgressBar1.Maximum = dic.Keys.Count();
                toolStripProgressBar1.Value = 0;
                foreach (string name in dic.Keys)
                {
                    toolStripProgressBar1.PerformStep();
                    IEnumerable<XElement> elis = root.Elements("Spieler");
                    IEnumerable<XElement> Spieler =
                       from el in root.Elements("Spieler")
                       where ((string)el.Element("Name").Value).Equals(name)
                       select el;
                    XElement els = null;
                    if (Spieler.Count() > 0)
                        els = Spieler.First<XElement>();
                    // spieler gibts schon
                    if (els != null)
                    {
                        List<DateTime> Datumliste = dic[name];
                        foreach (DateTime dat in Datumliste)
                        {
                            els.Element("Zeiten").Add(new XElement("Zeit", dat.ToString()));
                        }

                    }
                    else
                    {
                        XElement player = new XElement("Spieler", new XElement("Name", name), new XElement("Zeiten"));
                        root.Add(player);
                        List<DateTime> Datumliste = dic[name];
                        foreach (DateTime dat in Datumliste)
                        {
                            player.Element("Zeiten").Add(new XElement("Zeit", dat.ToString()));
                        }
                    }
                }
                if (File.Exists(fileName))
                    File.Delete(fileName);
                this.Validate();
                UseWaitCursor = true;
                this.Cursor = Cursors.WaitCursor;
                root.Save(fileName);
                UseWaitCursor = false;
                this.Cursor = Cursors.Default;
               
            }
            catch (Exception)
            {
                MessageBox.Show("Fehler beim Laden der XML-Datei");
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
             Dictionary<string, List<DateTime>> dates;
             textBox2.Text += Environment.NewLine;
             if (textBox2.Text.Contains("Universumsnews"))
            {
                dates = DateofZeitung(textBox2.Text);
            }
            else
            {
                dates = Dateof(textBox2.Text);
            }
            AddToXml(dates);
            removeData();
              
            textBox2.Text = String.Empty;
            fillComboBox();
            tspCNames_SelectedIndexChanged(null, null);
            loadStatData();
        }

        public Dictionary<string, List<DateTime>> DateofZeitung(String feld)
        {

            Dictionary<string, List<DateTime>> result = new Dictionary<string, List<DateTime>>();
            Regex MyRegex = new Regex(
      "(?<Year>(?:\\d{4}|\\d{2}))-(?<Month>\\d{1,2})-(?<Day>\\d{1,2" +
      "}).\r\n(?<hour>\\d{1,2}):(?<min>\\d{1,2}):(?<sec>\\d{1,2})(?<f" +
      "ill>.*)\\s(?<name>\\S*).vs.",
    RegexOptions.IgnoreCase
    | RegexOptions.CultureInvariant
    | RegexOptions.IgnorePatternWhitespace
    | RegexOptions.Compiled
    );


            MatchCollection Matches = MyRegex.Matches(feld);

            foreach (Match match in Matches)
            {
                if (match.Groups["fill"].Value.Contains("Krieg:")) continue;
                String name = match.Groups["name"].Value;
                if (result.ContainsKey(name))
                {
                    result[name].Add(new DateTime(int.Parse(match.Groups["Year"].Value), int.Parse(match.Groups["Month"].Value), int.Parse(match.Groups["Day"].Value), int.Parse(match.Groups["hour"].Value), int.Parse(match.Groups["min"].Value), int.Parse(match.Groups["sec"].Value)));
                }
                else
                {
                    result.Add(name, new List<DateTime>());
                    result[name].Add(new DateTime(int.Parse(match.Groups["Year"].Value), int.Parse(match.Groups["Month"].Value), int.Parse(match.Groups["Day"].Value), int.Parse(match.Groups["hour"].Value), int.Parse(match.Groups["min"].Value), int.Parse(match.Groups["sec"].Value)));
             
                }
            }//end foreach
            return result;

        }

        public Dictionary<string, List<DateTime>> Dateof(String feld)
        {

            Dictionary<string, List<DateTime>> result = new Dictionary<string, List<DateTime>>();
            Regex MyRegex = new Regex(
             "(?<Year>(?:\\d{4}|\\d{2}))-(?<Month>\\d{1,2})-(?<Day>\\d{1,2" +
                 "}).\r\n(?<hour>\\d{1,2}):(?<min>\\d{1,2}):(?<sec>\\d{1,2})",
                 RegexOptions.IgnoreCase
                 | RegexOptions.CultureInvariant
              | RegexOptions.IgnorePatternWhitespace
                 | RegexOptions.Compiled
                 );


            MatchCollection Matches = MyRegex.Matches(feld);

            foreach (Match match in Matches)
            {
                String res = match.Value;
                int index = feld.IndexOf(res);
                int index2 = feld.IndexOf('\n', index);
                String zeile ;
                try
                {
                    zeile = feld.Substring(index, index2 - index);
                    if (zeile.Length == res.Length + 1) continue;
                }
                catch (Exception)
                {
                    continue;
                }
              
                if (zeile.Contains("(PM/A/X)"))
                {
                    int indexVOn = zeile.IndexOf("von");
                    String name = zeile.Substring(indexVOn + 3);
                    name = name.Remove(name.IndexOf("(PM/A"));
                    name = name.Trim();
                    if (result.ContainsKey(name))
                    {
                        result[name].Add(DateTime.Parse(res.Trim()));
                    }
                    else
                    {
                        result.Add(name, new List<DateTime>());
                        result[name].Add(DateTime.Parse(res.Trim()));
                    }

                }
                else if (zeile.Split('\t').Count() <= 3 && (zeile.Split('\t').Count() > 1))
                {
                    zeile = zeile.Substring(zeile.IndexOf(res) + res.Length+1);
                    String name = zeile.Substring(0, zeile.IndexOf('\t')).Trim();
                    if (result.ContainsKey(name))
                    {
                        result[name].Add(DateTime.Parse(res.Trim()));
                    }
                    else
                    {
                        result.Add(name, new List<DateTime>());
                        result[name].Add(DateTime.Parse(res.Trim()));
                    }
                }
                else 
                {


                    zeile = zeile.Substring(zeile.IndexOf(res) + res.Length);
                    zeile = zeile.Substring(zeile.IndexOfAny(new char[] { ' ', '\t' }) + 1);
                    zeile = zeile.Substring(zeile.IndexOfAny(new char[] { ' ', '\t' }) + 1);
                    String name = zeile.Substring(zeile.IndexOfAny(new char[] { ' ', '\t' }) + 1);
                    name = name.Trim();
                    if (result.ContainsKey(name))
                    {
                        result[name].Add(DateTime.Parse(res.Trim()));
                    }
                    else
                    {
                        result.Add(name, new List<DateTime>());
                        result[name].Add(DateTime.Parse(res.Trim()));
                    }
                }
              

            }//end foreach
            return result;

        }

        private void FrmOnlineZeitenTool_Load(object sender, EventArgs e)
        {

            if (!File.Exists("Zeiten.xml"))
            {
                MessageBox.Show("Keine Zeiten gefunden!, Zeiten.xml Datei fehlt");
                 return;
            }
            fillComboBox();
            createDatasource();
            loadStatData();
            this.TopMost = false;
        }

        private void fillComboBox()
        {
            try
            {
                List<string> names = new List<string>();
                tspCNames.Items.Clear();
                XElement root = XElement.Load(fileName);
                IEnumerable<XElement> spieler = root.Elements("Spieler");
                foreach (XElement elem in spieler)
                {
                    tspCNames.Items.Add(elem.Element("Name").Value);
                }
                
            }
            catch (Exception)
            {
                MessageBox.Show("Fehler beim laden der XML-Datei");
            }
          
         }

        private void createDatasource()
        {
            DataTable datasource = new DataTable();
            datasource.Columns.Add("Zeit", typeof(DateTime));

            datasource.Columns.Add("Monday", typeof(Int32));
            datasource.Columns.Add("Tuesday", typeof(Int32));
            datasource.Columns.Add("Wednesday", typeof(Int32));
            datasource.Columns.Add("Thursday", typeof(Int32));
            datasource.Columns.Add("Friday", typeof(Int32));
            datasource.Columns.Add("Saturday", typeof(Int32));
            datasource.Columns.Add("Sunday", typeof(Int32));

            DateTime dt = new DateTime(2008, 1, 1, 0, 0, 0);

            for (int i = 0; i <= (((60*24) / TEIL_DER_STUNDE)); i++)
            {
                if (dt.Minute == 0 && dt.Hour == 0 && datasource.Rows.Count > 1) continue;
                DataRow row = datasource.NewRow();
                row["Zeit"] = dt;
                dt = dt.AddMinutes(TEIL_DER_STUNDE);
                
                datasource.Rows.Add(row);
            }
            dgVKalender.DataSource = datasource;
        }

        private List<DateTime> DatenFürSpieler(string Spielername)
        {
            try
            {
            List<DateTime> Dati = new List<DateTime>();

            XElement root = XElement.Load(fileName);
            IEnumerable<XElement> elis = root.Elements("Spieler");
            IEnumerable<XElement> Spieler =
                   from el in root.Elements("Spieler")
                   where (string)el.Element("Name").Value == Spielername
                   select el;
            try
            {
                 IEnumerable<XElement> datumKnoten = Spieler.First<XElement>().Element("Zeiten").Descendants();

                 foreach (XElement zeit in datumKnoten)
                 {
                     Dati.Add(DateTime.Parse(zeit.Value));
                 }
            }
            catch (Exception)
            {
            }
            Dati.Sort();
            return Dati;
            }
            catch (Exception)
            {
                MessageBox.Show("Fehler beim laden der XML-Datei");
            }
            return null;
            
        }

        private List<DateTime> DatenFürSpielerAbdatum(string Spielername, DateTime abDatum)
        {
            try
            {
                List<DateTime> Dati = new List<DateTime>();

                XElement root = XElement.Load(fileName);
                IEnumerable<XElement> elis = root.Elements("Spieler");
                IEnumerable<XElement> Spieler =
                       from el in root.Elements("Spieler")
                       where (string)el.Element("Name").Value == Spielername
                       select el;
                try
                {
                    IEnumerable<XElement> datumKnoten = Spieler.First<XElement>().Element("Zeiten").Descendants();

                    foreach (XElement zeit in datumKnoten)
                    {
                        DateTime datum = DateTime.Parse(zeit.Value);
                        if (datum.CompareTo(abDatum)>=0)
                            Dati.Add(DateTime.Parse(zeit.Value));
                    
                    }
                }
                catch (Exception)
                {
                }
                Dati.Sort();
                return Dati;
            }
            catch (Exception)
            {
                MessageBox.Show("Fehler beim laden der XML-Datei");
            }
            return null;

        }

        private void removeData()
        {
            
            tsStatusLabel.Text = "keine Systemraids erkannt";
            try
            {
                XElement root = XElement.Load(fileName);
                IEnumerable<XElement> elis = root.Elements("Spieler");
                toolStripProgressBar1.Maximum = elis.Count();
                toolStripProgressBar1.Value = 0;
                foreach (XElement spieler in elis)
                {
                    List<DateTime> datumsliste = DatenFürSpieler(spieler.Element("Name").Value);
                    toolStripProgressBar1.PerformStep();
                    this.Validate();
                    List<DateTime> result = new List<DateTime>();
                    DateTime lastone = DateTime.MinValue;
                    foreach (DateTime dt in datumsliste)
                    {
                        if (lastone == DateTime.MinValue)
                        {
                            lastone = dt;
                            result.Add(dt);
                        }
                        else if (Math.Abs((lastone - dt).TotalMinutes) > 15)
                        {
                            lastone = dt;
                            result.Add(dt);
                        }
                        else
                        {
                            tsStatusLabel.Text = "mindestens einen Systemraid erkannt";
                        }
                    }
                    spieler.Element("Zeiten").RemoveNodes();
                    foreach (DateTime dt in result)
                    {
                        spieler.Element("Zeiten").Add(new XElement("Zeit", dt.ToString()));
                    }
                }
                if (File.Exists(fileName))
                    File.Delete(fileName);
                this.Validate();
                UseWaitCursor = true;
                this.Cursor = Cursors.WaitCursor;
                root.Save(fileName);
                UseWaitCursor = false;
                this.Cursor = Cursors.Default;
            }
            catch (Exception)
            {
                MessageBox.Show("Fehler beim laden der XML-Datei");
            }
        }

        private void tspCNames_SelectedIndexChanged(object sender, EventArgs e)
        {
            tsLGesammt.Text = "Übersicht";
            createDatasource();
            if (tspCNames.Text == String.Empty) return;
            
            DataTable tabelle1 = dgVKalender.DataSource as DataTable;

             foreach(DayOfWeek MyEnum in Enum.GetValues(typeof(DayOfWeek)))
             {
                 List<DateTime> dates = DatenFürSpieler(tspCNames.Text);
                 IEnumerable<DateTime> wochentage =
                   from tag in dates
                   where tag.DayOfWeek == MyEnum
                   select tag;

                 foreach (DateTime dt in wochentage)
                 {
                     Console.Out.WriteLine(dt);

                     int tempminutes = dt.Hour * 60 + dt.Minute;
                     int rowindex =   tempminutes / TEIL_DER_STUNDE;
                    // int rowindex = dt.Hour * (60 / TEIL_DER_STUNDE) + dt.Minute / TEIL_DER_STUNDE;
                      try
                     {
                         tabelle1.Rows[rowindex][MyEnum.ToString()] = (int)tabelle1.Rows[rowindex][MyEnum.ToString()] + 1;
                         int value = (int)tabelle1.Rows[rowindex][MyEnum.ToString()];
                         dgVKalender.Rows[rowindex].Cells[translateEnum(MyEnum.ToString())].Style.BackColor = Color.FromArgb(100, 255 - value * 10, 255 - value * 10);
                     }
                     catch (Exception)
                     {
                         if (rowindex < tabelle1.Rows.Count)
                         {
                             tabelle1.Rows[rowindex][MyEnum.ToString()] = 1;
                             dgVKalender.Rows[rowindex].Cells[translateEnum(MyEnum.ToString())].Style.BackColor = Color.FromArgb(100, 255, 255);
                         }
                     }
                 }
             }//end foreach


            //MOnths
             this.monthCalendar1.RemoveAllBoldedDates();
             monthCalendar2.ResetDateInfo();
            UpdateKalender(tspCNames.Text);
             this.monthCalendar1.UpdateBoldedDates();

            }

        private String translateEnum(String enumeratio)
        {
            if (enumeratio.Equals("Monday"))
            {
                return "Mo";
            }
            else if (enumeratio.Equals("Tuesday"))
            {
                return "Di";
            }
            else if (enumeratio.Equals("Wednesday"))
            {
                return "Mi";
            }
            else if (enumeratio.Equals("Thursday"))
            {
                return "Do";
            }
            else if (enumeratio.Equals("Friday"))
            {
                return "Fr";
            }
            else if (enumeratio.Equals("Saturday"))
            {
                return "Sa";
            }
            else if (enumeratio.Equals("Sunday"))
            {
                return "So";
            }
            else return "Default";
        }

        private void dgVKalender_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                DataTable tabelle1 = dgVKalender.DataSource as DataTable;
                int value = (int)tabelle1.Rows[e.RowIndex][e.ColumnIndex];
                dgVKalender.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.FromArgb(value * 10, value * 10, value * 10);
            }
            catch (Exception)
            {
            }
          
        }

        private void toolStripComboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            TEIL_DER_STUNDE = int.Parse(toolStripComboBox1.Text);
            createDatasource();
            tspCNames_SelectedIndexChanged(null,null);
        }


        private void button1_Click(object sender, EventArgs e)
        {
            DialogResult res = openFileDialog1.ShowDialog();
            if (res == DialogResult.OK)
            {
                
                XElement root = XElement.Load(openFileDialog1.FileName);

                Dictionary<string, List<DateTime>> result = new Dictionary<string, List<DateTime>>();
                
               // MessageBox.Show("gefundene Spieler: in Datei: " + openFileDialog1.FileName + " "  + root.Elements("Spieler").Count());
                toolStripProgressBar1.Maximum = root.Elements("Spieler").Count();
                toolStripProgressBar1.Value = 0;
                

                foreach (XElement Spieler in root.Elements("Spieler"))
                {
                    
                 IEnumerable<XElement> datumKnoten = Spieler.Element("Zeiten").Descendants();

                 if (result.ContainsKey(Spieler.Element("Name").Value))
                 {
                        foreach (XElement zeit in datumKnoten)
                        {
                            result[Spieler.Element("Name").Value].Add(DateTime.Parse(zeit.Value));
                        }
                 }else
                 {
                     result.Add(Spieler.Element("Name").Value, new List<DateTime>());
                     foreach (XElement zeit in datumKnoten)
                     {
                            result[Spieler.Element("Name").Value].Add(DateTime.Parse(zeit.Value));
                     }
                 }
                 toolStripProgressBar1.PerformStep();
                }
                AddToXml(result);
            }
            removeData();
            fillComboBox();
            tspCNames_SelectedIndexChanged(null, null);
            loadStatData();
        }

   

        private List<DateTime> DatenFürSpielerWeek(string Spielername,int week)
        {
          try
          {
            List<DateTime> Dati = new List<DateTime>();

            XElement root = XElement.Load(fileName);
            IEnumerable<XElement> elis = root.Elements("Spieler");
            IEnumerable<XElement> Spieler =
                   from el in root.Elements("Spieler")
                   where (string)el.Element("Name").Value == Spielername
                   select el;
            try
            {
                IEnumerable<XElement> datumKnoten = Spieler.First<XElement>().Element("Zeiten").Descendants();

                foreach (XElement zeit in datumKnoten)
                {
                    DateTime datum = DateTime.Parse(zeit.Value);
                     System.Globalization.CultureInfo myCI = new CultureInfo("de");
                    if ( myCI.Calendar.GetWeekOfYear(datum, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday) == week)
                        Dati.Add(DateTime.Parse(zeit.Value));
                }
            }
            catch (Exception)
            {
            }
            Dati.Sort();
            return Dati ;
          }
          catch (Exception)
          {
              MessageBox.Show("Fehler beim laden der XML-Datei");
          }
            return null;
        }

        private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
        {
            tsLGesammt.Text = "Wochenübersicht";
            
            createDatasource();

            DateTime ausg = DateTime.Parse(dateTimePicker1.Text);
            System.Globalization.CultureInfo myCI = new CultureInfo("de");
            int week = myCI.Calendar.GetWeekOfYear(ausg, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
               
            if (tspCNames.Text == String.Empty) return;
            DataTable tabelle1 = dgVKalender.DataSource as DataTable;
            foreach (DayOfWeek MyEnum in Enum.GetValues(typeof(DayOfWeek)))
            {
                List<DateTime> dates = DatenFürSpielerWeek(tspCNames.Text, week);
                IEnumerable<DateTime> wochentage =
                  from tag in dates
                  where tag.DayOfWeek == MyEnum
                  select tag;

                foreach (DateTime dt in wochentage)
                {
                    Console.Out.WriteLine(dt);
                    int rowindex = dt.Hour * (60 / TEIL_DER_STUNDE) + dt.Minute / TEIL_DER_STUNDE;
                    try
                    {
                        tabelle1.Rows[rowindex][MyEnum.ToString()] = (int)tabelle1.Rows[rowindex][MyEnum.ToString()] + 1;
                        int value = (int)tabelle1.Rows[rowindex][MyEnum.ToString()];
                        dgVKalender.Rows[rowindex].Cells[translateEnum(MyEnum.ToString())].Style.BackColor = Color.FromArgb(100, 255 - value * 10, 255 - value * 10);
                    }
                    catch (Exception)
                    {
                        tabelle1.Rows[rowindex][MyEnum.ToString()] = 1;
                        dgVKalender.Rows[rowindex].Cells[translateEnum(MyEnum.ToString())].Style.BackColor = Color.FromArgb(100, 255, 255);
                    }
                }
            }//end foreach

        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (textBox3.Text == string.Empty || textBox1.Text == string.Empty || tBName.Text == string.Empty)
            {
                MessageBox.Show("Falsche eingaben!");
                return;
            }
            try
            {

                XElement root = XElement.Load(fileName);
                IEnumerable<XElement> elis = root.Elements("Spieler");
                IEnumerable<XElement> Spieler =
                        from el in root.Elements("Spieler")
                        where (string)el.Element("Name").Value == tBName.Text
                        select el;
                XElement els = null;
                if (Spieler.Count() > 0)
                    els = Spieler.First<XElement>();
                // spieler gibts schon
                if (els != null)
                {
                    DateTime dat = DateTime.Parse(dateTimePicker2.Text);
                    DateTime dat2 = new DateTime(dat.Year, dat.Month, dat.Day, int.Parse(textBox1.Text), int.Parse(textBox3.Text), 0);
                    els.Element("Zeiten").Add(new XElement("Zeit", dat2.ToString()));

                }
                else
                {
                    XElement player = new XElement("Spieler", new XElement("Name", tBName.Text), new XElement("Zeiten"));
                    root.Add(player);
                    DateTime dat = DateTime.Parse(dateTimePicker2.Text);
                    DateTime dat2 = new DateTime(dat.Year, dat.Month, dat.Day, int.Parse(textBox1.Text), int.Parse(textBox3.Text), 0);
                    player.Element("Zeiten").Add(new XElement("Zeit", dat2.ToString()));
                }

                root.Save(fileName);
                fillComboBox();
                tspCNames_SelectedIndexChanged(null, null);
            }
            catch (Exception)
            {
                MessageBox.Show("Fehler beim laden der XML-Datei oder fehlerhafte Eingaben");
            }
        }


        private void loadStatData()
        {
            XElement root = XElement.Load(fileName);
            IEnumerable<XElement> elis = root.Elements("Spieler");
            tslCountPlayer.Text = elis.Count().ToString();
            int countEvents = 0;
            foreach (XElement spieler in elis)
            {
                countEvents += spieler.Element("Zeiten").Descendants().Count();
            }
            tsplcounterEreignisse.Text = countEvents.ToString();
        }

        private void dTStartSuche_ValueChanged(object sender, EventArgs e)
        {
            tsLGesammt.Text = "Datumsübersicht";

            createDatasource();

            DateTime ausg = DateTime.Parse(dTStartSuche.Text);
          
            if (tspCNames.Text == String.Empty) return;
            DataTable tabelle1 = dgVKalender.DataSource as DataTable;
            foreach (DayOfWeek MyEnum in Enum.GetValues(typeof(DayOfWeek)))
            {
                List<DateTime> dates = DatenFürSpielerAbdatum(tspCNames.Text, ausg);
                IEnumerable<DateTime> wochentage =
                  from tag in dates
                  where tag.DayOfWeek == MyEnum
                  select tag;

                foreach (DateTime dt in wochentage)
                {
                    int rowindex = dt.Hour * (60 / TEIL_DER_STUNDE) + dt.Minute / TEIL_DER_STUNDE;
                    try
                    {
                        tabelle1.Rows[rowindex][MyEnum.ToString()] = (int)tabelle1.Rows[rowindex][MyEnum.ToString()] + 1;
                        int value = (int)tabelle1.Rows[rowindex][MyEnum.ToString()];
                        dgVKalender.Rows[rowindex].Cells[translateEnum(MyEnum.ToString())].Style.BackColor = Color.FromArgb(100, 255 - value * 10, 255 - value * 10);
                    }
                    catch (Exception)
                    {
                        tabelle1.Rows[rowindex][MyEnum.ToString()] = 1;
                        dgVKalender.Rows[rowindex].Cells[translateEnum(MyEnum.ToString())].Style.BackColor = Color.FromArgb(100, 255, 255);
                    }
                }
            }//end foreach
        }


        private void UpdateKalender(String Spielername)
        {
            List<DateTime> Dati = new List<DateTime>();

            XElement root = XElement.Load(fileName);
            IEnumerable<XElement> elis = root.Elements("Spieler");
            IEnumerable<XElement> Spieler =
                   from el in root.Elements("Spieler")
                   where (string)el.Element("Name").Value == Spielername
                   select el;
            try
            {
                IEnumerable<XElement> datumKnoten = Spieler.First<XElement>().Element("Zeiten").Descendants();
                Dictionary<DateTime, Int32> dates = new Dictionary<DateTime, int>();

                monthCalendar2.ResetDateInfo();

                
                foreach (XElement zeit in datumKnoten)
                {
                    DateTime datum = DateTime.Parse(zeit.Value);
                    if (dates.Keys.Contains(datum))
                    {
                        dates[datum] += 1;
                    }
                    else
                    {
                        dates.Add(datum, 1);
                    }
                    
                }
              
                int index = 0;
                datesForPlayer = new Pabo.Calendar.DateItem[dates.Keys.Count()];
                datesForPlayer.Initialize();
                for (int i = 0; i < dates.Keys.Count(); i++)
                    datesForPlayer[i] = new Pabo.Calendar.DateItem();

                foreach (DateTime key in dates.Keys)
                {
                    this.monthCalendar1.AddBoldedDate(key);
                    int evennumber = dates[key];
                    datesForPlayer[index].Date = new DateTime(key.Year, key.Month, key.Day);
                    datesForPlayer[index].Text = evennumber.ToString();
                    if (evennumber > 0 && evennumber < 5)
                    {
                        datesForPlayer[index].BackColor1 = Color.Yellow;
                        datesForPlayer[index].BackColor2 = Color.GhostWhite;
                        datesForPlayer[index].DateColor = Color.Red;
                    }
                    else if (evennumber >= 5 && evennumber < 10)
                    {
                        datesForPlayer[index].BackColor1 = Color.Orange;
                        datesForPlayer[index].BackColor2 = Color.GhostWhite;
                        datesForPlayer[index].DateColor = Color.Red;
                    }
                    else if (evennumber >= 10)
                    {
                        datesForPlayer[index].BackColor1 = Color.Red;
                        datesForPlayer[index].BackColor2 = Color.GhostWhite;
                        datesForPlayer[index].DateColor = Color.Black;
                    }

                    index++;

                }

                this.monthCalendar2.AddDateInfo(datesForPlayer);
                monthCalendar2.SelectDate(monthCalendar1.SelectionStart);
            }
            catch (Exception)
            {
            }
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            monthCalendar2.SelectDate(monthCalendar1.SelectionStart);
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {

            if (tspCNames.Text.Length <= 0) return;

            DialogResult result =  MessageBox.Show("Sind Sie sich sicher das Sie den Spieler " + tspCNames.Text + " löschen wollen?", "löschen", MessageBoxButtons.YesNo);

            if (result.Equals(DialogResult.Yes))
            {

                XElement root = XElement.Load(fileName);
                IEnumerable<XElement> elis = root.Elements("Spieler");
                IEnumerable<XElement> Spieler =
                       from el in root.Elements("Spieler")
                       where (string)el.Element("Name").Value == tspCNames.Text
                       select el;
                try
                {
                    Spieler.Remove();
                }
                catch (Exception)
                {
                }
                root.Save(fileName);
                fillComboBox();
                tspCNames_SelectedIndexChanged(null, null);
                loadStatData();
            }
        }

 
     
    }
}
